<template>
  <div class="pagination">
    <button @click="$emit('changePageNo',pageNo - 1)" :disabled="pageNo == 1">上一页</button>

    <button v-if="startEnd.start > 1" @click="$emit('changePageNo',1)">1</button>
    <button v-if="startEnd.start > 2">...</button>

    <button
    :class="{ active:pageNo == page }"
      v-for="page in startEnd.end"
      :key="page"
      v-if="page >= startEnd.start"
      @click="$emit('changePageNo',page)"
    >
      {{ page }}
    </button>

    <button  v-if="startEnd.end < pageTotal-1">···</button>
    <button v-if="startEnd.end < pageTotal" @click="$emit('changePageNo',pageTotal)">{{pageTotal}}</button>

    <button @click="$emit('changePageNo',pageNo + 1)" :disabled="pageNo == pageTotal">下一页</button>

    <button style="margin-left: 30px">共 {{total}} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: {
    pageNo: {
      //当前页
      type: Number,
      required: true,
    },
    pageSize: {
      // 每页条数
      type: Number,
      required: true,
    },
    total: {
      //总条数
      type: Number,
      required: true,
    },
    pageCount: {
      //连续数
      type: Number,
      default: 5,
    },
  },
  computed: {
    // 总页码
    pageTotal() {
      return Math.ceil(this.total / this.pageSize);
    },
    // 起始位置  结束位置
    startEnd() {
      //    当前页   每页条数  总条数  连续数     总页数
      let { pageNo, pageSize, total, pageCount, pageTotal } = this;
      let start = 0
      let end = 0; //起始位置,结束位置
      if (pageCount > pageTotal) {
        (start = 1), (end = pageTotal);
      } else {
        start = pageNo - (pageCount - 1) / 2;
        end = pageNo + (pageCount - 1) / 2;
        // 边界情况
        if (start < 1) {
          start = 1;
          end = pageCount;
        }
        if (end > pageTotal) {
          end = pageTotal;
          start = pageTotal - pageCount + 1;
        }
      }
      return { start, end };
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
